import store from '../../services/store'
import second from '../../services/second'
import goods from '../../services/goods'

Page({

    /**
     * 页面的初始数据
     */
    data: {
        configData: {},
        goodsList:[],
        currentGoodsTag:'recommend',
        // 瀑布流相关数据
        waterfallData: {
            leftColumn: [],
            rightColumn: []
        },
        showVirtual: false,
        virtualGoodsList: [],
        // 高度缓存
        goodsHeightCache: new Map(),

        secondData: [],
        recommendsData: [],
        // 今日日期
        todayDate: '',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setTodayDate();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getConfig();
        this.getRecommendGoodsList();
        this.getSecondData();
        this.getRecommendsData();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    async getConfig() {
        const res = await store.config();
        if (res.success) {
            this.setData({
                configData: res.data
            })
        }
    },

    goGoodsIndex(e) {
        const id = e.currentTarget.dataset.id;
        const url = e.currentTarget.dataset.url;

        if(url == null || url == ''){
            wx.navigateTo({
                url: `/store/pages/index/index?cid=${id}`
            })
        }else{
            console.log(url);
            wx.navigateTo({
                url: url
            })
        }
        
    },

    async getRecommendGoodsList() {
        const res = await store.recommendGoodsList(this.data.currentGoodsTag);
        if (res.success) {
            this.setData({
                goodsList: res.data.goodsList
            });
            // 处理瀑布流布局
            await this.processWaterfallLayout(res.data.goodsList);
        }
    },

    // 处理瀑布流布局
    async processWaterfallLayout(goodsList) {
        if (!goodsList || goodsList.length === 0) {
            this.setData({
                waterfallData: {
                    leftColumn: [],
                    rightColumn: []
                }
            });
            return;
        }

        // 分批处理商品列表
        await this.processGoodsInBatches(goodsList, 5);
    },

    // 分批处理商品列表
    async processGoodsInBatches(goodsList, batchSize = 5) {
        const batches = [];
        for (let i = 0; i < goodsList.length; i += batchSize) {
            batches.push(goodsList.slice(i, i + batchSize));
        }
        
        let leftColumn = [];
        let rightColumn = [];
        let leftHeight = 0;
        let rightHeight = 0;
        
        for (const batch of batches) {
            // 渲染当前批次到虚拟容器
            this.setData({
                showVirtual: true,
                virtualGoodsList: batch
            });
            
            // 等待渲染完成
            await this.waitForRender();
            
            // 获取当前批次的高度
            const heights = await this.getBatchHeights(batch);
            
            // 分配到列
            batch.forEach((goods, index) => {
                const height = heights[index] || 400; // 默认高度
                
                if (leftHeight <= rightHeight) {
                    leftColumn.push(goods);
                    leftHeight += height;
                } else {
                    rightColumn.push(goods);
                    rightHeight += height;
                }
            });
            
            // 更新显示
            this.setData({
                waterfallData: {
                    leftColumn: [...leftColumn],
                    rightColumn: [...rightColumn]
                }
            });
        }
        
        // 隐藏虚拟容器
        this.setData({
            showVirtual: false,
            virtualGoodsList: []
        });
    },

    // 等待渲染完成
    waitForRender() {
        return new Promise(resolve => {
            setTimeout(resolve, 150);
        });
    },

    // 获取批次高度
    async getBatchHeights(batch) {
        return new Promise((resolve) => {
            const query = wx.createSelectorQuery();
            
            batch.forEach((goods, index) => {
                query.select(`#virtual-goods-${index}`).boundingClientRect();
            });
            
            query.exec((res) => {
                const heights = res.map(item => item ? item.height : 400);
                resolve(heights);
            });
        });
    },

    changeGoodsTag(e) {
        const tag = e.currentTarget.dataset.tag;
        this.setData({
            currentGoodsTag: tag
        },function(){
            this.getRecommendGoodsList();
        })
    },

    toGoodsDetail(e) {
        const id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/store/pages/goods/detail?id=${id}`
        })
    },

    toSearch() {
        wx.navigateTo({
            url: `/store/pages/index/search`
        })
    },

    async getSecondData() {
        const res = await second.getTodayGoods();
        if (res.success) {
            // 为每个商品添加图片加载状态
            const secondData = res.data.map(item => ({
                ...item,
                imageLoaded: false
            }));
            this.setData({
                secondData: secondData
            })
        }
    },

    // 图片加载完成事件
    onImageLoad(e) {
        const index = e.currentTarget.dataset.index;
        const id = e.currentTarget.dataset.id;
        
        // 延迟一点时间再触发动画，让用户看到加载过程
        setTimeout(() => {
            const secondData = this.data.secondData.map((item, idx) => {
                if (idx === parseInt(index)) {
                    return {
                        ...item,
                        imageLoaded: true
                    };
                }
                return item;
            });
            
            this.setData({
                secondData: secondData
            });
        }, 200);
    },

    async getRecommendsData() {
        const res = await goods.recommends();
        if (res.success) {
            this.setData({
                recommendsData: res.data
            })
        }
    },

    // 设置今日日期
    setTodayDate() {
        const today = new Date();
        const month = today.getMonth() + 1; // getMonth() 返回 0-11，需要加1
        const day = today.getDate();
        const todayDate = `${month}月${day}日`;
        
        this.setData({
            todayDate: todayDate
        });
    }
    
})